//
//  DKWebViewController.m
//  DanKU
//
//  Created by 吴斌 on 2023/10/7.
//

#import "DKWebViewController.h"
#import <WebKit/WebKit.h>
@interface DKWebViewController ()<WKNavigationDelegate,WKUIDelegate,UIScrollViewDelegate>
@property (nonatomic, strong) WKWebView *dk_webView;
@property (nonatomic, strong) UIProgressView *dk_progressView;
@property (nonatomic, copy) NSString *dk_WebUrl;
@property (nonatomic,assign) BOOL isShowNavBar;
@property (nonatomic,strong) UILabel *dk_navTitleLab;
@end

@implementation DKWebViewController
- (void)dealloc {
    [_dk_webView removeObserver:self forKeyPath:@"title"];
    [_dk_webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
- (WKWebView *)dk_webView {
    if (!_dk_webView) {
        _dk_webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:[self webViewConfiguration]];
        _dk_webView.navigationDelegate = self;
        _dk_webView.UIDelegate = self;
        _dk_webView.scrollView.bounces = false;//禁止滑动
        _dk_webView.scrollView.delegate = self;
        _dk_webView.backgroundColor = self.view.backgroundColor;
        _dk_webView.scrollView.backgroundColor = self.view.backgroundColor;
        _dk_webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    return _dk_webView;
}

- (UIProgressView *)dk_progressView {
    if (!_dk_progressView) {
        _dk_progressView = [[UIProgressView alloc] init];
        _dk_progressView.progress = 0.0;
        _dk_progressView.progressTintColor = UIColor.blueColor;
    }
    return _dk_progressView;
}
- (WKWebViewConfiguration *)webViewConfiguration {
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences.javaScriptEnabled = YES;
    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    config.suppressesIncrementalRendering = YES; // 是否支持记忆读取
    [config.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
    [config setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"];
    
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    NSMutableString *javascript = [NSMutableString string];
    //禁止长按
    [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];
    //禁止选择
    [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];
    //禁止缩放
    [javascript appendString:@"('head').append('<meta name=\"viewport\" content=\"width=device-width,minimum-scale=1,maximum-scale=0,initial-scale=1,user-scalable=0\">');"];
    WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [wkUController addUserScript:noneSelectScript];
    // 通过JS与webview内容交互
    config.userContentController = wkUController;
    return config;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    [self creatWebView];
    [self loadWebUrl];
}
- (instancetype)initWithUrl:(NSString *)url withIsNavBar:(BOOL)isShow{
    if (self = [super init]) {
        _isShowNavBar = isShow;
        _dk_WebUrl = url;
        NSLog(@"打开webUrl地址:%@",_dk_WebUrl);
        
    }
    return self;
}
- (void)loadWebUrl{
//    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:_dk_WebUrl]];
//    [request setValue:@"text/javascript" forHTTPHeaderField:@"Content-Type"];
//    [_dk_webView loadRequest:request];
    NSString* htmlstr = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:_dk_WebUrl]encoding:NSUTF8StringEncoding error:nil];
    [_dk_webView loadHTMLString:htmlstr baseURL:[NSURL URLWithString:_dk_WebUrl]];
}
- (void)creatWebView{
    CGFloat navHeight = 0;
    if(_isShowNavBar){
        navHeight = DK_SafeAreaNav_H;
        [self creatNavView];
    }
    [self.view addSubview:self.dk_webView];
    [_dk_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(@(navHeight));
    }];
    // progress
    [self.view addSubview:self.dk_progressView];
    [_dk_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.equalTo(@(1.0));
    }];
    
    if([_dk_WebUrl isEqualToString:DK_PrivacyAgreement]){
        self.dk_navTitleLab.text = @"Privacy Agreement";
    }else if([_dk_WebUrl isEqualToString:DK_RegisterAgreement]){
        self.dk_navTitleLab.text = @"Register Agreement";
    }else if([_dk_WebUrl isEqualToString:DK_LoanAgreement]){
        self.dk_navTitleLab.text = @"Loan Agreement";
    }
    if([_dk_WebUrl isEqualToString:DK_PrivacyAgreement]||[_dk_WebUrl isEqualToString:DK_RegisterAgreement]||[_dk_WebUrl isEqualToString:DK_LoanAgreement]){
        [self requestUserBrhavRecord];
    }
    //监听 标题/进度
    [_dk_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    [_dk_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)requestUserBrhavRecord{
    NSMutableDictionary *agrmeentDic = [[NSMutableDictionary alloc] init];
    if([_dk_WebUrl isEqualToString:DK_PrivacyAgreement]){
        [agrmeentDic setValue:@"Privacy" forKey:@"type"];
    }else if([_dk_WebUrl isEqualToString:DK_RegisterAgreement]){
        [agrmeentDic setValue:@"Register" forKey:@"type"];
    }else if([_dk_WebUrl isEqualToString:DK_LoanAgreement]){
        [agrmeentDic setValue:@"Loan" forKey:@"type"];
    }
    [DKPublicHttp apiUserBrhavRecordForAPI:agrmeentDic withPageName:DK_Agreement withAction:DK_ActionEnter complete:^{
            
    } fail:^{
            
    }];
}
- (void)creatNavView{
    UIView * dk_navView = [[UIView alloc] init];
    dk_navView.userInteractionEnabled = YES;
    dk_navView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:dk_navView];
    [dk_navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(DK_IsWidthScale(0)));
        make.height.equalTo(@(DK_SafeAreaNav_H));
        make.left.right.equalTo(@(DK_IsWidthScale(0)));
    }];
    //返回
    UIButton * dk_navBackBtn = [[UIButton alloc] init];
    [dk_navBackBtn setBackgroundImage:DK_GetImage(@"dk_registerBack") forState:UIControlStateNormal];
    [dk_navBackBtn addTarget:self action:@selector(popVCAction) forControlEvents:UIControlEventTouchUpInside];
    [dk_navView addSubview:dk_navBackBtn];
    [dk_navBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(DK_IsWidthScale(15)));
        make.top.equalTo(@(DK_IsWidthScale(12)+DK_SafeAreaTop));
        make.width.equalTo(@(DK_IsWidthScale(20)));
        make.height.equalTo(@(DK_IsWidthScale(20)));
    }];
    self.dk_navTitleLab = [[UILabel alloc] init];
    self.dk_navTitleLab.textColor = DK_Hex(@"#0000000");
    self.dk_navTitleLab.font = DK_FONT_Regular(17);
    [dk_navView addSubview:self.dk_navTitleLab];
    [self.dk_navTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@(DK_IsWidthScale(0)));
        make.centerY.equalTo(dk_navBackBtn);
    }];
}
#pragma mark -- WKScriptMessageHandler
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == _dk_webView) {
            if (_dk_progressView.hidden) {
                _dk_progressView.hidden = NO;
                return;
            }
            [_dk_progressView setAlpha:1.0f];
            [_dk_progressView setProgress:_dk_webView.estimatedProgress animated:YES];
            if(_dk_webView.estimatedProgress >= 1.0f) {
                _dk_progressView.hidden = YES;
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else {
        if([keyPath isEqualToString:@"title"]){
            self.dk_navTitleLab.text = _dk_webView.title;
        }
    }
}
#pragma marl -- UIScrollViewDelegate
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
    [scrollView setValue:@(NO) forKeyPath:@"pinchGestureRecognizer.enabled"];
}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return nil;
}
#pragma mark ---- 导航配置
- (void)popVCAction{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
